package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public RecommendUser todayBest(Long toUserId) {
//        db.getCollection('recommend_user').find({toUserId:1}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        query.with(Sort.by(Sort.Direction.DESC,"score")); // 根据得分（缘分值）降序
        query.skip(0).limit(1); // 只查询第一条数据
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendUserList(Integer page, Integer pagesize,Long toUserId) {
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        /*query.with(Sort.by(Sort.Direction.DESC,"score")); // 根据得分（缘分值）降序
        query.skip((page-1)*pagesize).limit(pagesize); //*/
        query.with(PageRequest.of(page-1,pagesize,Sort.by(Sort.Direction.DESC,"score")));

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize,(int)count,recommendUserList);
    }

    @Override
    public Long queryScore(Long userId, Long toUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
//        这个推荐用户有可能查不到 给一个默认值
        if(recommendUser==null){
            return 88L;
        }
        return recommendUser.getScore().longValue();
    }
}
